package com.duan.luren.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.duan.luren.common.BusinessExceptionUtils;
import com.duan.luren.config.RabbitMQConfiguration;
import com.duan.luren.dto.UserRegisterRequest;
import com.duan.luren.mapper.UserMapper;
import com.duan.luren.mq.sender.IMsgSender;
import com.duan.luren.po.UserPO;
import com.duan.luren.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserPO> implements IUserService {

    @Autowired
    private IMsgSender msgSender;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String register(UserRegisterRequest req) {
        // 1、声明式事务开启
        // 2、本地业务处理
        UserPO userPO = new UserPO();
        userPO.setId(IdUtil.fastSimpleUUID());
        userPO.setName(req.getName());
        this.save(userPO);
        //3、消息表t_msg写入记录
        this.msgSender.sendWithBody(RabbitMQConfiguration.User.EXCHANGE, null,userPO);
        this.msgSender.sendWithBody(RabbitMQConfiguration.User2.EXCHANGE, null,userPO);

        return userPO.getId();
        // 事务结束
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String registerError(UserRegisterRequest req) {
        UserPO userPO = new UserPO();
        userPO.setId(IdUtil.fastSimpleUUID());
        userPO.setName(req.getName());
        this.save(userPO);

        //发送用户注册消息
        this.msgSender.sendWithBody(RabbitMQConfiguration.User.EXCHANGE, RabbitMQConfiguration.User.ROUTING_KEY, userPO);

        throw BusinessExceptionUtils.businessException("故意失败，看消息投递情况");
    }
}
